<?php
/**
 * #Celebrate Shieh
 *             ,%%%%%%%%,
 *           ,%%/\%%%%/\%%
 *          ,%%%\c "" J/%%%
 * %.       %%%%/ o  o \%%%
 * `%%.     %%%%    _  |%%%
 *  `%%     `%%%%(__Y__)%%'
 *  //       ;%%%%`\-/%%%'
 * ((       /  `%%%%%%%'
 *  \\    .'          |
 *   \\  /       \  | |
 *    \\/         ) | |
 *     \         /_ | |__
 *     (___________))))))) 攻城湿
 *
 *        _       _
 * __   _(_)_   _(_) __ _ _ __
 * \ \ / / \ \ / / |/ _` |'_ \
 *  \ V /| |\ V /| | (_| | | | |
 *   \_/ |_| \_/ |_|\__,_|_| |_|
 */

namespace App\Services;

use App\Models\Blog\Search;
use Illuminate\Http\Request;

class SearchService
{

    use Service;

    /**
     * 博客搜索首页
     *
     * @param Request $request
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function SearchIndexService( $request )
    {
        $select = [ 'id', 'title', 'count', 'user_id', 'status', 'updated_at', 'static' ];
        $where  = function ( $query ) use ( $request ) {
            if ( $request->filled('static') && $request->input('static') != '-1' ) $query->where('static', $request->input('static'));
            if ( $request->filled('title') ) $query->where('title', $request->input('title'));
            $query->where('status', 1);
        };
        $with   = [
            'user' => function ( $query ) {
                $query->select('id', 'name');
            },
        ];
        $search = Search::GetModel($where, $with, $select);
        $search->appends([
            'title'  => $request->input('title'),
            'static' => $request->input('static'),
        ])->render();
        return view('blog.search.index', compact('search', 'request'));
    }

    /**
     * 博客搜索删除
     *
     * @param         $id
     * @param Request $request
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function SearchDestroyService( $id, $request )
    {
        $ajax = $request->ajax();
        Search::DestroyModel($id);
        if ( $ajax ) return data(NULL, $this->getErrorCode()::message(204));
        else return back()->with('success', $this->getErrorCode()::message(204));
    }

    /**
     * 修改博客搜索是否显示
     *
     * @param $id
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function SearchStatusService( $id )
    {
        $select = [ 'id', 'static' ];
        $where  = function ( $query ) use ( $id ) {
            $query->where('id', $id);
        };
        $search = Search::FirstModel($where, [], $select);
        if ( $search->static == 1 ) $static = 2;
        else $static = 1;
        $search->static = $static;
        $search->save();
        return back()->with('success', $this->getErrorCode()::message(210));
    }
}
